#include "Statistics.h"
#include "NCManager.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <pthread.h>

using namespace std;

vector<int> Statistics::curlErrorCounter;
pthread_mutex_t Statistics::curlErrorMutex;
pthread_mutex_t Statistics::LP_Mutex;
pthread_mutex_t Statistics::HF_Mutex;
pthread_mutex_t Statistics::CC_Mutex;
int Statistics::LP_time;
int Statistics::LP_calls;
int Statistics::HF_time;
int Statistics::HF_calls;
int Statistics::CC_time;
int Statistics::CC_calls;


void Statistics::init()
{
	pthread_mutex_init(&Statistics::curlErrorMutex, NULL);
	pthread_mutex_init(&Statistics::LP_Mutex, NULL);
	pthread_mutex_init(&Statistics::HF_Mutex, NULL);
	pthread_mutex_init(&Statistics::CC_Mutex, NULL);
	Statistics::LP_time=0;
	Statistics::LP_calls=0;
	Statistics::HF_time=0;
	Statistics::HF_calls=0;
	
	for(int i=0;i <=80;i++)
		curlErrorCounter.push_back(0);
}

void Statistics::addCurlError(int err)
{
	Statistics::curlErrorCounter[err] = Statistics::curlErrorCounter[err] + 1;
}

void Statistics::curlErrorReport()
{
	time_t now;
	now = time(&now);
	ofstream file;
	file.open("curlReport.log");
	file << "Starting Log Report @ " << now << endl;
	file << "########################################" << endl;
	for(int i=0;i< Statistics::curlErrorCounter.size(); i++)
	{
		file << "Erro: " << i << "Total: " << Statistics::curlErrorCounter[i] <<endl;
	}
	file.close();
}

void Statistics::statsReport()
{
	time_t now;
	now = time(&now);
	ofstream file,  file1;
	file.open("statsReport.log");
	file1.open("graphicReport.log", iostream::app | iostream::out);
	file << "Starting Log Report @ " << now << endl;
	file << "########################################" << endl;
	file << " PAGES D/L " << NCManager::visitedSites << endl;
	file << " ROBOTS D/L " << NCManager::fetchedRobots << endl;
	file << " ########################################" << endl;
//	file << " CANONICAL CONV: " << endl;
//	file << " \t CALLS: " << CC_calls << " \t TIME: " << CC_time << endl;
//	file << " HTML FETCHER: " << endl;
//	file << " \t CALLS: " << HF_calls << " \t TIME: " << HF_time << endl;
//	file << " LINK PARSER: " << endl;
//	file << " \t CALLS: " << LP_calls << " \t TIME: " << LP_time << endl;
	file1 << now << " " << NCManager::visitedSites << endl;
	file.close();
	file1.close();
}